# plugs/worktimer.py
#
#

""" maintain timer of time spend working """

__copyright__ = 'this file is in the public domain'
__author__ = 'Michiel van Vaardegem (michiel@freecode.nl)'

from gozerbot.generic import elapsedstring
from gozerbot.persist import Persist
from gozerbot.users import users
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.datadir import datadir
from gozerbot.plughelp import plughelp
import time

plughelp.add('worktimer', 'start/stop worktimer')

# The work times
worktimes = Persist(datadir + '/worktimes')

if not worktimes.data:
    worktimes.data = {}
    
def handle_workstart(bot, ievent):
    """ store work start time """
    # Get the user
    username = users.getname(ievent.userhost)
    # Check data construction
    try:
        worktimes.data[username]
    except KeyError:
        worktimes.data[username] = [0, 0, 0] # startime, totaltime, running
    # Update the data
    if worktimes.data[username][2]:
        ievent.reply('worktimer already started')
        return
    worktimes.data[username][0] = time.time()
    worktimes.data[username][2] = 1
    worktimes.save()
    ievent.reply("worktimer started")

# Handle a workstop
def handle_workstop(bot, ievent):
    """ stop work timer """
    # Get the user
    username = users.getname(ievent.userhost)
    # Check data construction
    try:
        worktimes.data[username]
    except KeyError:
        worktimes.data[username] = [0, 0, 0] # startime, totaltime, running
    # Check if timer is running
    if not worktimes.data[username][2]:
        ievent.reply("worktimer isn't running")
        return
    # Calculate the diff
    diff = time.time() - worktimes.data[username][0]
    # Update the data
    worktimes.data[username][1] += diff
    worktimes.data[username][2] = 0
    worktimes.save()
    ievent.reply("worktimer stoped. total time worked: %s" % \
elapsedstring(worktimes.data[username][1]))

def handle_workreset(bot, ievent):
    """ reset work timer """
    # Get the user
    username = users.getname(ievent.userhost)
    # Check data construction
    try:
        worktimes.data[username]
    except KeyError:
        worktimes.data[username] = [0, 0, 0] # startime, totaltime, running
    # Reset the total time
    worktimes.data[username][0] = 0
    worktimes.data[username][1] = 0
    worktimes.data[username][2] = 0
    worktimes.save()
    ievent.reply("worktimer is reset")

cmnds.add('wstart', handle_workstart, 'USER')
examples.add('wstart', 'start work timer', 'wstart')
cmnds.add('wstop', handle_workstop, 'USER')
examples.add('wstop', 'stop work timer', 'wstop')
cmnds.add('wreset', handle_workreset, 'USER')
examples.add('wreset', 'reset work timer', 'wreset')
